package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.JacksonObjectMapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.IEmployeeService;
import jdk.nashorn.internal.ir.RuntimeNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 登入系统
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<Employee> Login(@RequestBody Employee employee, HttpServletRequest request){

        if(employee == null){
            return R.error("您的用户名不存在");
        }
        if(employee.getUsername()==null || employee.getPassword()==null){
            return R.error("用户名或密码不能为空");
        }
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<Employee>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee exitsEpl = employeeService.getOne(qw);

        if(exitsEpl==null || !exitsEpl.getPassword().equals(password)){
            return R.error("用户名或密码错误");
        }
        if(exitsEpl.getStatus() == 0){
            return R.error("账号已被禁用");
        }if(exitsEpl.getPassword().equals(password)){
            exitsEpl.setPassword(null);
            request.getSession().setAttribute("loginSuccess",exitsEpl.getId());
            return R.success(exitsEpl);
        }
        return R.error("您的登录有误,请检查后重新登录");

    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<Employee> logout(HttpServletRequest request){
        request.getSession().invalidate();
        return R.success(null);

    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> addEmployee(@RequestBody Employee employee, HttpServletRequest Request){
        log.info("新增员工信息:{}", employee.toString());

        //设置默认初始密码为123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //设置初始时间和更新时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //获取当前登录用户的id
        Long empId = (Long) Request.getSession().getAttribute("loginSuccess");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     *分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        //1、分页参数封装  new Page<Employee>(当前页，每页大小)
        Page<Employee> ep = new Page<>(page, pageSize);

        //2、封装查询条件 new LambdaQueryWrapper() : where name like '%xxx%'
        // like(条件,xx,xx)
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //3、添加默认排序 orderByDesc() :  order by update_time desc
        qw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(ep,qw);
        return R.success(ep);
    }

    /**
     * 根据员工修改成员信息
     */

    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpServletRequest request){

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        Long empId = (Long) request.getSession().getAttribute("loginSuccess");
        //1、修改员工数据 update_time
        employee.setUpdateTime(LocalDateTime.now());

        //2、修改员工数据 update_user 从sesion中获取员工id
        employee.setUpdateUser(empId);
        //3、调用业务层修改员工信息 updateById()
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){

        Employee employee = employeeService.getById(id);
        if(employee!=null){
            return R.success(employee);
        }
        return R.error("查无此人");
    }
}
